<template>
    <div class="practice-test">
        <!-- 顶部标题 -->
        <div class="header">
            <van-icon name="arrow-left" size="20" @click="goBack" class="back-icon" />
            <h2>{{ currentCategoryName }}测试</h2>
            <div class="progress">
                第 {{ currentIndex + 1 }} 题 / 共 {{ questions.length }} 题
            </div>
        </div>

        <!-- 题目区域 -->
        <div class="question-container">
            <div v-if="loading" class="loading">
                <van-loading size="24px">加载中...</van-loading>
            </div>

            <template v-else>
                <!-- 题目卡片 -->
                <div class="question-card">
                    <!-- 题目标题区域 -->
                    <div class="question-header">
                        <van-icon :name="questionTypeIcon" size="18" color="#1989fa" />
                        <span class="question-type">{{ questionTypeText }}</span>
                    </div>

                    <!-- 题目内容 -->
                    <div class="question-content">
                        <h3>{{ currentQuestion.content }}</h3>
                    </div>

                    <!-- 根据题目类型显示不同的输入组件 -->
                    <div class="answer-area">
                        <!-- 单选题 -->
                        <template v-if="currentQuestion.questionType === 1">
                            <van-radio-group v-model="currentAnswer">
                                <van-cell-group>
                                    <van-cell v-for="(option, key) in parsedOptions" :key="key" clickable
                                        :title="`${key}. ${option}`" @click="handleOptionClick(key)"
                                        class="option-cell">
                                        <template #right-icon>
                                            <van-radio :name="key" />
                                        </template>
                                    </van-cell>
                                </van-cell-group>
                            </van-radio-group>
                        </template>

                        <!-- 多选题 -->
                        <template v-if="currentQuestion.questionType === 2">
                            <van-checkbox-group v-model="multiAnswers">
                                <van-cell-group>
                                    <van-cell v-for="(option, key) in parsedOptions" :key="key" clickable
                                        :title="`${key}. ${option}`" @click="toggleMultiAnswer(key)"
                                        class="option-cell">
                                        <template #right-icon>
                                            <van-checkbox :name="key" shape="square" />
                                        </template>
                                    </van-cell>
                                </van-cell-group>
                            </van-checkbox-group>
                        </template>

                        <!-- 判断题 -->
                        <template v-if="currentQuestion.questionType === 3">
                            <van-radio-group v-model="currentAnswer">
                                <van-cell-group>
                                    <van-cell title="正确" clickable @click="currentAnswer = 'T'" class="option-cell">
                                        <template #right-icon>
                                            <van-radio name="T" />
                                        </template>
                                    </van-cell>
                                    <van-cell title="错误" clickable @click="currentAnswer = 'F'" class="option-cell">
                                        <template #right-icon>
                                            <van-radio name="F" />
                                        </template>
                                    </van-cell>
                                </van-cell-group>
                            </van-radio-group>
                        </template>

                        <!-- 填空题 -->
                        <template v-if="currentQuestion.questionType === 4">
                            <div class="fill-blank-tip">
                                <van-icon name="info" color="#1989fa" />
                                <span>请在下方输入框中填写答案</span>
                            </div>
                            <van-field v-model="currentAnswer" type="textarea" rows="3" placeholder="请输入您的答案..."
                                clearable class="fill-blank-input" />
                        </template>

                        <!-- 简答题 -->
                        <template v-if="currentQuestion.questionType === 5">
                            <div class="fill-blank-tip">
                                <van-icon name="info" color="#1989fa" />
                                <span>请详细回答以下问题</span>
                            </div>
                            <van-field v-model="currentAnswer" type="textarea" rows="5" placeholder="请输入您的详细回答..."
                                clearable class="fill-blank-input" />
                        </template>
                    </div>
                </div>
            </template>
        </div>

        <!-- 导航按钮 - 修改为固定定位 -->
        <div class="navigation-buttons-fixed">
            <van-button round type="default" size="large" :disabled="currentIndex === 0" @click="prevQuestion"
                class="nav-button">
                <van-icon name="arrow-left" /> 上一题
            </van-button>
            <van-button v-if="currentIndex < questions.length - 1" round type="primary" size="large"
                @click="nextQuestion" class="nav-button">
                下一题 <van-icon name="arrow" />
            </van-button>
            <van-button v-else round type="success" size="large" @click="submitPractice" class="nav-button">
                <van-icon name="passed" /> 提交测试
            </van-button>
        </div>

        <!-- 确认提交对话框 -->
        <van-dialog v-model:show="showConfirmDialog" :title="dialogContent.title" :message="dialogContent.message"
            show-cancel-button :confirm-button-text="dialogContent.confirmText"
            :cancel-button-text="dialogContent.cancelText" :confirm-button-color="dialogContent.confirmColor"
            @confirm="handleConfirmSubmit" @cancel="handleCancelSubmit" :before-close="beforeDialogClose" />

        <!-- 提交成功对话框 - 修改为带两个按钮的版本 -->
        <van-dialog v-model:show="showSuccessDialog" title="提交成功" message="您的测试已成功提交！" show-cancel-button
            confirm-button-text="查看答题情况" cancel-button-text="返回主页" confirm-button-color="#07c160"
            @confirm="handleViewDetail" @cancel="handleReturnHome" />

        <!-- 提交失败对话框 -->
        <van-dialog v-model:show="showErrorDialog" title="提交失败" message="提交过程中出现错误，请稍后再试。" confirm-button-text="确定"
            confirm-button-color="#ee0a24" @confirm="handleErrorConfirm" />


    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showLoadingToast, showSuccessToast, Dialog } from 'vant'
import { getRandomQuestions, submitPractices } from '@/api/practice'
import type { Question, UserAnswer, PracticeSubmission } from '@/types/question_category/practice'

const router = useRouter()
const route = useRoute()

const goBack = () => {
    router.go(-1)
}

const successRecordNo = ref('') // 用于存储提交成功的记录编号



// 从路由参数获取分类信息
const categoryNo = ref(route.query.categoryNo as string)
const questionCount = Number(route.query.questionCount) || 5
const currentCategoryName = ref('')

// 对话框相关状态
const showConfirmDialog = ref(false)
const showSuccessDialog = ref(false)
const showErrorDialog = ref(false)
const isSubmitting = ref(false)

// 对话框内容状态
const dialogContent = ref({
    title: '提交确认',
    message: '',
    confirmText: '确认提交',
    cancelText: '继续作答',
    confirmColor: '#07c160'
})

// 问题列表和当前状态
const questions = ref<Question[]>([])
const currentIndex = ref(0)
const loading = ref(true)

// 记录开始时间
const startTime = ref(new Date())

// 答案存储
const currentAnswer = ref('')
const multiAnswers = ref<string[]>([])
const userAnswers = ref<Record<string, string>>({})

// 当前问题
const currentQuestion = computed(() => questions.value[currentIndex.value])

// 题目类型图标和文本
const questionTypeIcon = computed(() => {
    switch (currentQuestion.value.questionType) {
        case 1: return 'circle'
        case 2: return 'checked'
        case 3: return 'todo-list'
        case 4: return 'edit'
        case 5: return 'description'
        default: return 'question'
    }
})

const questionTypeText = computed(() => {
    switch (currentQuestion.value.questionType) {
        case 1: return '单选题'
        case 2: return '多选题'
        case 3: return '判断题'
        case 4: return '填空题'
        case 5: return '简答题'
        default: return '未知题型'
    }
})

// 解析选项JSON
const parsedOptions = computed(() => {
    try {
        return JSON.parse(currentQuestion.value.options || '{}')
    } catch {
        return {}
    }
})

// 处理选项点击
const handleOptionClick = (key: string) => {
    currentAnswer.value = key
}

// 初始化加载问题
onMounted(async () => {
    // 记录开始时间
    startTime.value = new Date()

    try {
        const res = await getRandomQuestions(categoryNo.value, questionCount)
        questions.value = res.data
        if (questions.value.length > 0) {
            currentCategoryName.value = questions.value[0].categoryName
            initAnswerForQuestion(currentQuestion.value)
        }
    } catch (error) {
        console.error('加载问题失败:', error)
    } finally {
        loading.value = false
    }
})

// 初始化当前问题的答案
const initAnswerForQuestion = (question: Question) => {
    if (question.questionType === 2) {
        multiAnswers.value = userAnswers.value[question.questionNo]?.split(',') || []
    } else {
        currentAnswer.value = userAnswers.value[question.questionNo] || ''
    }
}

// 切换多选题选项
const toggleMultiAnswer = (key: string) => {
    const index = multiAnswers.value.indexOf(key)
    if (index > -1) {
        multiAnswers.value.splice(index, 1)
    } else {
        multiAnswers.value.push(key)
    }
}

// 保存当前答案
const saveCurrentAnswer = () => {
    const question = currentQuestion.value
    const answer = question.questionType === 2
        ? multiAnswers.value.sort().join(',')
        : currentAnswer.value

    if (answer) {
        userAnswers.value[question.questionNo] = answer
    }
}

// 检查未作答题目
const checkUnansweredQuestions = () => {
    // 检查所有题目是否都有有效答案
    const unanswered = questions.value.filter(question => {
        const answer = userAnswers.value[question.questionNo]

        // 对于填空题和简答题，空字符串不算有效答案
        if (question.questionType === 4 || question.questionType === 5) {
            return !answer || answer.trim() === ''
        }

        // 对于多选题，空数组不算有效答案
        if (question.questionType === 2) {
            return !answer || answer === ''
        }

        // 其他类型题目
        return !answer
    })

    // 如果所有题目都未作答
    if (unanswered.length === questions.value.length) {
        return {
            valid: false,
            message: '您还没有回答任何题目，请至少完成一题后再提交。'
        }
    }

    // 如果有部分题目未作答
    if (unanswered.length > 0) {
        const unansweredText = unanswered
            .map((q, i) => `${currentIndexToQuestionNumber(q.questionNo)}. ${q.content.substring(0, 20)}...`)
            .join('\n')

        return {
            valid: false,
            message: `以下题目未作答:\n${unansweredText}`
        }
    }

    return { valid: true }
}

// 根据问题编号获取题目序号
const currentIndexToQuestionNumber = (questionNo: string) => {
    const index = questions.value.findIndex(q => q.questionNo === questionNo)
    return index >= 0 ? index + 1 : '?'
}



// 上一题
const prevQuestion = () => {
    saveCurrentAnswer()
    if (currentIndex.value > 0) {
        currentIndex.value--
        initAnswerForQuestion(currentQuestion.value)
    }
}

// 下一题
const nextQuestion = () => {
    saveCurrentAnswer()
    if (currentIndex.value < questions.value.length - 1) {
        currentIndex.value++
        initAnswerForQuestion(currentQuestion.value)
    }
}

// 提交练习 - 只负责显示确认对话框
const submitPractice = () => {
    saveCurrentAnswer()

    // 检查未作答题目
    const checkResult = checkUnansweredQuestions()

    // 设置对话框内容
    if (!checkResult.valid) {
        dialogContent.value = {
            title: '提交确认',
            message: checkResult.message,
            confirmText: '确认提交',
            cancelText: '继续作答',
            confirmColor: '#07c160'
        }
    } else {
        dialogContent.value = {
            title: '提交确认',
            message: '您已完成所有题目，确认要提交吗？',
            confirmText: '确认提交',
            cancelText: '再检查一下',
            confirmColor: '#07c160'
        }
    }

    // 显示确认对话框
    showConfirmDialog.value = true
}

// 格式化日期为 yyyy-MM-dd HH:mm:ss (GMT+8)
const formatLocalDateTime = (date: Date): string => {
  const pad = (num: number) => num.toString().padStart(2, '0')
  
  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1)
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 确认提交处理
const handleConfirmSubmit = async () => {
    isSubmitting.value = true
    const toast = showLoadingToast({
        message: '提交中...',
        forbidClick: true,
        duration: 0
    })

    try {
        // 收集所有答案
        const answers: UserAnswer[] = questions.value.map(question => ({
            questionNo: question.questionNo,
            answer: userAnswers.value[question.questionNo] || '',
        }))

        const recordNo = `REC${Date.now()}`
        successRecordNo.value = recordNo // 保存recordNo

        console.log('格式化后的开始时间:', formatLocalDateTime(startTime.value))

        const submission: PracticeSubmission = {
            recordNo: recordNo,
            userNo: localStorage.getItem("userNo") || "defaultUserNo",
            categoryNo: categoryNo.value,
            startTime: formatLocalDateTime(startTime.value), // 使用格式化后的时间
            answers,
        }

        await submitPractices(submission)

        // 提交成功，显示成功提示
        showConfirmDialog.value = false
        showSuccessDialog.value = true
    } catch (error) {
        console.error('提交失败:', error)
        // 提交失败提示
        showConfirmDialog.value = false
        showErrorDialog.value = true
    } finally {
        toast.close()
        isSubmitting.value = false
    }
}

// 成功确认处理
const handleSuccessConfirm = () => {
    showSuccessDialog.value = false
    router.push('/')
}

// 错误确认处理
const handleErrorConfirm = () => {
    showErrorDialog.value = false
}

// 查看详情处理函数
const handleViewDetail = () => {
    showSuccessDialog.value = false
    // router.push({
    //     path: '/recordDetail/:recordNo',
    //     query: { recordNo: successRecordNo.value }
    // })
    const recordNo = successRecordNo.value
    router.push(`/recordDetail/${recordNo}`);
}

// 返回主页处理函数
const handleReturnHome = () => {
    showSuccessDialog.value = false
    router.push('/')
}

</script>

<style scoped>
.practice-test {
  padding: 0;
  height: 100vh;
  display: flex;
  flex-direction: column;
  font-size: 16px;
  background-color: #f7f8fa;
  position: relative;
}

.header {
  position: relative;
  margin-bottom: 0;
  text-align: center;
  padding: 12px 16px;
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  z-index: 1;
  flex-shrink: 0; /* 防止header被压缩 */
}

.back-icon {
  position: absolute;
  left: 16px;
  top: 50%;
  transform: translateY(-50%);
  color: #1989fa;
  cursor: pointer;
}

.header h2 {
  margin: 0 0 0 24px; /* 给返回按钮留出空间 */
  color: #1989fa;
  font-size: 18px;
  font-weight: bold;
}

.progress {
  margin-top: 4px;
  color: #666;
  font-size: 13px;
}

.question-container {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  padding-bottom: 80px; /* 给底部按钮留出空间 */
  /* 确保内容能完全展开 */
  display: flex;
  flex-direction: column;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  flex: 1; /* 加载状态也撑满空间 */
}

.question-card {
  background: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  margin-bottom: 12px;
  flex: 1; /* 卡片撑满可用空间 */
  display: flex;
  flex-direction: column;
  min-height: 0; /* 防止flex容器溢出 */
}

.question-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
  flex-shrink: 0; /* 防止标题区域被压缩 */
}

.question-content {
  margin-bottom: 16px;
  flex-shrink: 0; /* 固定题目内容高度 */
}

.question-content h3 {
  margin: 0;
  font-size: 17px;
  line-height: 1.6;
  font-weight: 500;
}

.answer-area {
  margin-top: 8px;
  flex: 1; /* 答案区域撑满剩余空间 */
  min-height: 0; /* 防止flex容器溢出 */
  overflow-y: auto; /* 答案区域可滚动 */
}

.option-cell {
  margin-bottom: 8px;
  border-radius: 8px;
  background-color: #fafafa;
  transition: all 0.2s;
}

.option-cell:hover {
  background-color: #f0f7ff;
}

.fill-blank-tip {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  color: #666;
  font-size: 14px;
  flex-shrink: 0;
}

.fill-blank-tip .van-icon {
  margin-right: 6px;
}

.fill-blank-input {
  border-radius: 8px;
  background-color: #fafafa;
  border: 1px solid #eee;
  flex: 1; /* 输入框撑满空间 */
  min-height: 0; /* 防止flex容器溢出 */
}

/* 修改后的固定底部导航按钮样式 */
.navigation-buttons-fixed {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  gap: 12px;
  padding: 12px 16px;
  background-color: white;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.08);
  z-index: 10;
  /* 圆角阴影 */
  border-radius: 20px 20px 0 0;
}

.nav-button {
  flex: 1;
  font-size: 15px;
  height: 44px;
}

.nav-button .van-icon {
  vertical-align: middle;
  margin: 0 4px;
}
</style>